home *** CD-ROM | disk | FTP | other *** search
/ Magnum One / Magnum One (Mid-American Digital) (Disc Manufacturing).iso / d12 / cgazv5n4.arc / NUMBER.CPP < prev    next >
C/C++ Source or Header  |  1991-09-23  |  911b  |  29 lines

  1. //--- NUMBER.CPP ------------------------- Listing 3 -----------
  2. // Number the lines in a file (simple test of string class)
  3. // by Bruce Eckel. See Listing 1 for copyright information.
  4. //--------------------------------------------------------------
  5.  
  6. #include "stringc.h"
  7.  
  8. main(int argc, char * argv[]) {
  9.   if(argc < 2) {
  10.     fprintf(stderr, "usage: number filename\n");
  11.     exit(1);
  12.   }
  13.   FILE* fp = fopen(argv[1], "r");
  14.   if(fp == NULL) {
  15.     fprintf(stderr, "could not open %s\n", argv[1]);
  16.     exit(1);
  17.   }
  18.   const bsz = 80;  char buf[bsz];
  19.   for(int lines = 0;;) {
  20.     if(!fgets(buf, bsz, fp)) break;  // quit on end-of-file
  21.     buf[strlen(buf) -1] = '\0';  // erase terminating newline
  22.     string line(buf);  // create a string object from the buffer
  23.     sprintf(buf, "%d: ", lines);
  24.     line.prepend(buf);  // add line number
  25.     line.print();
  26.     lines++;
  27.   }
  28.   fclose(fp);
  29. }